﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Activation;
using System.ServiceModel;
using System.Web.Routing;
using System.Xml.Linq;

/// <summary>
/// 为了进一步拓展，才定义了自己的ServiceHostFactory
/// </summary>
public class MyServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        var result = base.CreateServiceHost(serviceType, baseAddresses);
        return result;
    }
}

public static class ServiceRegister
{

    /// <summary>
    /// 配置文件路径
    /// </summary>
    private const string _DefaultFilePath = "IoC.config";


    private static ServiceHostFactory wshf;
    /// <summary>
    /// 静态构造函数只执行一次
    /// </summary>
    static ServiceRegister()
    {
        wshf = new MyServiceHostFactory();
    }

    /// <summary>
    /// 通过反射注册服务
    /// </summary>
    public static void RegisterAllService()
    {
        foreach (var info in Initialization())
        {
            var sr = new ServiceRoute(info.Key, wshf, info.Value);
            RouteTable.Routes.Add(sr);
        }
    }

    /// <summary>
    /// 初始化配置文件
    /// 从配置文件中读取表与写站点的关系
    /// </summary>
    /// <returns></returns>
    private static Dictionary<string, Type> Initialization()
    {
        string configFilePath = cn.Util.WebConfig.ConfigFilePath + _DefaultFilePath;

        Dictionary<string, Type> dics = new Dictionary<string, Type>();

        var root = XElement.Load(configFilePath, LoadOptions.None);
        var allElement = from obj in root.Elements()
                         select obj;

        foreach (XElement host in allElement)
        {
            if (host.Name.LocalName != "Wcf")
            {
                continue;
            }

            //反射路径
            string reflectionPath = host.Attribute(XName.Get("reflectionPath")).Value;

            var assembly = System.Reflection.Assembly.Load(reflectionPath);


            //取类信息
            foreach (XElement cla in host.Elements())
            {
                //接口类名
                string interfaceName = cla.Attribute(XName.Get("interface")).Value;

                //命名空间路径
                string className = cla.Attribute(XName.Get("class")).Value;

                dics.Add(interfaceName+".svc", assembly.GetType(className));
            }

        }

        return dics;
    }


}
